package routes

import (
	"mumu_stock_trad/proxy"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

// InitRoute
func InitRoute(hub *proxy.Hub) *gin.Engine {
	router := gin.Default()

	// CORS 配置
	router.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},                                                // 允许所有域名
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, // 允许类型
		AllowHeaders:     []string{"Content-Type", "Authorization", "x-token"},         // 允许的请求头
		AllowCredentials: true,                                                         // 是否允许发送 Cookie
		MaxAge:           86400,                                                        // CORS 预检请求缓存的最大时长
	}))

	// 打印请求头中的 x-token
	router.Use(func(c *gin.Context) {
		// 获取请求头中的 x-token
		token := c.GetHeader("x-token")

		// 获取请求的 URL 路径
		urlPath := c.Request.URL.Path

		if token != "" {
			// 打印 x-token
			log.Info("Received x-token: ", token, " method: "+urlPath)
		} else {
			log.Info("No x-token in request;", " method: "+urlPath)
		}
		// 继续执行后续处理
		c.Next()
	})

	// 信任本地的代理
	router.SetTrustedProxies([]string{"127.0.0.1"})

	// 创建路由组
	sr := router.Group("/decs-mst/")
	{
		loadMisc(sr)

		loadAPI(sr, hub)
	}

	return router
}
